package com.ft.oa.service.development.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ft.oa.domain.Attachment;
import com.ft.oa.domain.customer.Customer;
import com.ft.oa.domain.development.*;
import com.ft.oa.domain.dto.ApiResult;
import com.ft.oa.domain.dto.development.DevNeedCategory;
import com.ft.oa.domain.dto.development.ProjectCondition;
import com.ft.oa.domain.dto.development.ProjectDto;
import com.ft.oa.domain.dto.knowledgeBase.AttachmentDto;
import com.ft.oa.domain.project.ExecProject;
import com.ft.oa.domain.project.ExecProjectContract;
import com.ft.oa.domain.project.ExecProjectStage;
import com.ft.oa.domain.sequence.CommonSequenceParams;
import com.ft.oa.domain.sys.SysUser;
import com.ft.oa.enums.DirectoryTypeEnum;
import com.ft.oa.enums.ManagerEnum;
import com.ft.oa.mapper.customer.CustomerMapper;
import com.ft.oa.mapper.customer.ExecProjectContractMapper;
import com.ft.oa.mapper.development.DevNeedInfoMapper;
import com.ft.oa.mapper.development.DevNeedIssueMapper;
import com.ft.oa.mapper.development.DevNeedMapper;
import com.ft.oa.mapper.development.NeedContractMapper;
import com.ft.oa.mapper.industrysMapper.DevNeedAnalyseMapper;
import com.ft.oa.mapper.project.ExecProjectMapper;
import com.ft.oa.mapper.sequence.CommonSequenceMapper;
import com.ft.oa.mapper.sys.SysUserMapper;
import com.ft.oa.service.development.DevNeedService;
import com.ft.oa.service.knowledgeBase.DirectoryService;
import com.ft.oa.service.project.ExecProjectService;
import com.ft.oa.service.sys.SysUserService;
import com.ft.oa.utils.SecurityUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class DevNeedServiceImpl implements DevNeedService {

    @Resource
    private DevNeedMapper devNeedMapper;
    @Resource
    private NeedContractMapper needContractMapper;
    @Resource
    private CustomerMapper customerMapper;
    @Resource
    private ExecProjectMapper execProjectMapper;
    @Resource
    private ExecProjectContractMapper execProjectContractMapper;
    @Resource
    private DirectoryService directoryService;
    @Resource
    private SysUserService sysUserService;
    @Resource
    private DevNeedInfoMapper devNeedInfoMapper;
    @Resource
    private DevNeedIssueMapper devNeedIssueMapper;
    @Resource
    private CommonSequenceMapper commonSequenceMapper;
    @Resource
    private DevNeedAnalyseMapper devNeedAnalyseMapper;
    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private ExecProjectService execProjectService;



    public static List<DevNeedCategory> categoryList = new ArrayList<>();
    public static Map<String, String> devCategory = new HashMap<>();

    static {
        categoryList.add(new DevNeedCategory(1, "合同需求"));
        categoryList.add(new DevNeedCategory(2, "售前需求"));
        categoryList.add(new DevNeedCategory(3, "售后需求"));
        categoryList.add(new DevNeedCategory(4, "规划需求"));

        devCategory.put("平台", "platform,PT");
        devCategory.put("系统", "system,XT");
        devCategory.put("组件", "components,ZJ");
        devCategory.put("功能点", "function,GN");

    }

    @Override
    @Transactional
    public ApiResult projectToNeed(DevNeed devNeed) {
        devNeed.setCategory(1);
        List<DevNeedInfo> infos = devNeed.getInfos();
        if(infos != null && infos.size() > 0){
            devNeed.setDevCreate(true);
        }
        //新增需求
        ApiResult add = this.add(devNeed);
        if(add.getCode() != 200){
            return add;
        }else {
            //新增研发需求

            if(infos != null && infos.size() > 0){
                infos.forEach(e->e.setDevNeedId(devNeed.getId()));
                this.createDevNeed(infos);
            }
            //修改项目创建需求
            LambdaUpdateChainWrapper<ExecProject> updateProjectWrapper = new LambdaUpdateChainWrapper<>(execProjectMapper);
            updateProjectWrapper.eq(ExecProject::getId, devNeed.getProjectId())
                    .set(ExecProject::getCreated, true)
                    .update();
            return ApiResult.simpleSuccess();
        }

    }

    @Override
    public ProjectDto projectInfo(ExecProject project) {
        ExecProject execProject = execProjectMapper.selectById(project.getId());

        ProjectDto projectDto = new ProjectDto();
        projectDto.setProjectId(execProject.getId());
        projectDto.setProjectName(execProject.getName());
        List<ExecProjectContract> projectContractList = this.projectContractList(execProject);
        projectDto.setProjectContractList(projectContractList);

        return projectDto;

    }

    @Override
    public Page<ExecProject> projectPage(ProjectCondition condition) {

        QueryWrapper<ExecProject> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .eq(ManagerEnum.GENERAL.toString().equals(SecurityUtils.getCurrentUser().getManager()),ExecProject::getCreator ,SecurityUtils.getCurrentUser().getId())
                .eq(ExecProject::getApprovalStatus, 1)
//                .like(StringUtils.hasText(condition.getName()), ExecProject::getName, condition.getName())
                .eq(StringUtils.hasText(condition.getParentProjectNumber()),ExecProject::getParentProjectNumber, condition.getParentProjectNumber())
                .like(StringUtils.hasText(condition.getProjectNumber()), ExecProject::getProjectNumber, condition.getProjectNumber())
                .eq(condition.getManager() != null, ExecProject::getResponsibilityUserId, condition.getManager())
                .eq(condition.getCreated() != null, ExecProject::getCreated, condition.getCreated()).orderByDesc( ExecProject::getId);

        Page<ExecProject> page = new Page<>(condition.getPage(), condition.getSize());
        Page<ExecProject> result = execProjectMapper.selectPage(page, wrapper);
        result.getRecords().forEach(e->{
            if(e.getAchment() != null){
                e.setAttachments(JSONObject.parseArray(e.getAchment(), AttachmentDto.class));
            }
        });

        return result;
    }

    @Override
    public List<ExecProjectStage> projectView(String projectNumber) {
        List<ExecProjectStage> execProjectStageList = execProjectService.selectStage(projectNumber);
        List<ExecProjectStage> collect = execProjectStageList.stream()
                .filter(execProjectStage -> null != execProjectStage.getStageName() && !"".equals(execProjectStage.getStageName())).collect(Collectors.toList());
        return collect;
    }

    @Override
    @Transactional
    public ApiResult confirm(DevNeed devNeed) {
        //根据id查询用户名
        SysUser user = sysUserMapper.selectById(devNeed.getChargePersonId());
        LambdaUpdateChainWrapper<DevNeed> wrapper = new LambdaUpdateChainWrapper<>(devNeedMapper);
        boolean update = wrapper.eq(DevNeed::getId, devNeed.getId())
                .eq(DevNeed::getDataState, 0)
                .set(DevNeed::getDataState, 2)
                .set(DevNeed::getChargePersonId,devNeed.getChargePersonId())
                .set(DevNeed::getChargePersonName,user.getNickname())
                .set(DevNeed::getConfirmTime,LocalDateTime.now())
                .update();
        return update ? ApiResult.simpleSuccess() :
                ApiResult.builder().code(20006).msg("确认失败，请联系管理员！").build();

    }

    @Override
    @Transactional
    public ApiResult issue(DevNeed devNeed) {


        //更新下发表 .
        DevNeedIssue issue = new DevNeedIssue(devNeed);
        issue.setDevNeedNo(generateDevNeedNo(devNeed.getDevNeedCategory()));
        int insert = devNeedIssueMapper.insert(issue);
        //修改需求状态
        List<Long> issueNeedList = devNeed.getIssueNeedList();
        if(issueNeedList == null || issueNeedList.size() < 1){
            return ApiResult.builder().code(20007).msg("未选择下发项！").build();
        }
        for (Long needId : issueNeedList) {
            LambdaUpdateChainWrapper<DevNeed> needWrapper = new LambdaUpdateChainWrapper<>(devNeedMapper);
            boolean update = needWrapper.eq(DevNeed::getId, needId)
                    .eq(DevNeed::getDataState, 2)
                    .set(DevNeed::getDataState, 5)
                    .set(DevNeed::getIssueId, issue.getId())
                    .update();
            if(!update){
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return ApiResult.builder().code(20008).msg("下发需求失败，需求状态异常！").build();
            }
        }

        return ApiResult.simpleSuccess();
    }

    @Override
    @Transactional
    public ApiResult issueRollback(DevNeedIssue issue) {

        //修改需求状态
        QueryWrapper<DevNeed> needWrapper = new QueryWrapper<>();
        needWrapper.lambda()
                .eq(DevNeed::getIssueId, issue.getId());

        List<DevNeed> needList = devNeedMapper.selectList(needWrapper);
        needList.forEach(
                need -> {
                    LambdaUpdateChainWrapper<DevNeed> needUpdateWrapper = new LambdaUpdateChainWrapper<>(devNeedMapper);
                    needUpdateWrapper.eq(DevNeed::getId, need.getId())
                            .set(DevNeed::getIssueId, null)
                            .set(DevNeed::getDataState, 2)
                            .update();
                }
        );

        //修改下发表状态
        LambdaUpdateChainWrapper<DevNeedIssue> issueUpdateWrapper = new LambdaUpdateChainWrapper<>(devNeedIssueMapper);
        issueUpdateWrapper.eq(DevNeedIssue::getId, issue.getId())
                .set(DevNeedIssue::getDataState, 1)
                .update();

        return ApiResult.simpleSuccess();
    }

    private String generateDevNeedNo(String name){

        String s = devCategory.get(name);
        String[] split = s.split(",");
        CommonSequenceParams params = new CommonSequenceParams();
        params.setSeqName(split[0]);
        commonSequenceMapper.getNextNo(params);


        return split[1] + String.format("%06d", params.getSeqNo());

    }

    @Override
    @Transactional
    public void reject(DevNeed devNeed) {
        LambdaUpdateChainWrapper<DevNeed> wrapper = new LambdaUpdateChainWrapper<>(devNeedMapper);
        boolean update = wrapper.eq(DevNeed::getId, devNeed.getId())
                .set(StringUtils.hasText(devNeed.getRejectReason()), DevNeed::getRejectReason, devNeed.getRejectReason())
                .set(DevNeed::getDataState, 3)
                .update();
    }

    @Override
    @Transactional
    public void close(DevNeed devNeed) {
        LambdaUpdateChainWrapper<DevNeed> wrapper = new LambdaUpdateChainWrapper<>(devNeedMapper);
        boolean update = wrapper.eq(DevNeed::getId, devNeed.getId())
                .set(StringUtils.hasText(devNeed.getCloseReason()), DevNeed::getCloseReason, devNeed.getCloseReason())
                .set(DevNeed::getDataState, 4)
                .update();
    }

    @Override
    public List<SysUser> preSaleList(DevNeed devNeed) {
        List<SysUser> sysUsers = sysUserService.listAll();
        return sysUsers;
    }

    @Override
    @Transactional
    public ApiResult edit(DevNeed devNeed) {
        //更新需求
        DevNeed one = devNeedMapper.selectById(devNeed.getId());
        if(one.getDataState() == 0 || one.getDataState() == 3 || one.getDataState() == 4){
            devNeed.setNeedNo(null);
            devNeed.setDataState(0);
            devNeedMapper.updateById(devNeed);
            updateNeedContract(devNeed, one);

        }else {
            return ApiResult.builder().code(20003).msg("当前状态无法修改").build();
        }

        return ApiResult.simpleSuccess();

    }

    private void updateNeedContract(DevNeed devNeed, DevNeed one) {
        //处理附件
        if(devNeed.getProjectId() == null){
            List<NeedContract> needContractList = devNeed.getNeedContractList();

            if(Objects.nonNull(needContractList)){

                LambdaUpdateChainWrapper<NeedContract> wrapper = new LambdaUpdateChainWrapper<>(needContractMapper);
                boolean update = wrapper.eq(NeedContract::getNeedId, one.getId())
                        .set(NeedContract::getDel, true)
                        .update();

                needContractList.forEach(
                        e->{
                            List<AttachmentDto> attachments = e.getAttachments();
                            String json = JSONObject.toJSONString(attachments);
                            e.setAttachment(json);
                            needContractMapper.insert(e);
                            //保存附件表
                            directoryService.saveProAttachment(
                                    attachments,
                                    DirectoryTypeEnum.DEV_NEED_PRO_CONTRACT.getCode(),
                                    e.getId().toString(),
                                    DirectoryTypeEnum.DEV_NEED_PRO_CONTRACT.getCode(),
                                    devNeed.getProjectName()
                            );
                        }
                );
            }
        }
    }

    @Override
    @Transactional
    public ApiResult add(DevNeed devNeed) {

        QueryWrapper<DevNeed> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .eq(DevNeed::getNeedNo, devNeed.getNeedNo());
        List<DevNeed> devNeeds = devNeedMapper.selectList(wrapper);
        if(devNeeds != null && devNeeds.size() > 0){
            return ApiResult.builder().code(20001).msg("需求编号已存在").build();
        }

        devNeed.setCreateTime(LocalDateTime.now());
        //更新需求
        devNeedMapper.insert(devNeed);
        saveNeedContract(devNeed);
        return ApiResult.simpleSuccess();
    }

    private void saveNeedContract(DevNeed devNeed) {
        //更新自定义合同
        if(devNeed.getProjectId() == null){
            List<NeedContract> needContractList = devNeed.getNeedContractList();

            if(Objects.nonNull(needContractList)){

                needContractList.forEach(
                        e->{
                            List<AttachmentDto> attachments = e.getAttachments();
                            String json = JSONObject.toJSONString(attachments);
                            e.setAttachment(json);
                            needContractMapper.insert(e);
                            //保存附件表
                            directoryService.saveProAttachment(
                                    attachments,
                                    DirectoryTypeEnum.DEV_NEED_PRO_CONTRACT.getCode(),
                                    e.getId().toString(),
                                    DirectoryTypeEnum.DEV_NEED_PRO_CONTRACT.getCode(),
                                    devNeed.getProjectName()
                                    );
                        }
                );
            }
        }
    }


    @Override
    public List<ExecProject> projectList(DevNeed devNeed) {

        QueryWrapper<ExecProject> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .eq(ExecProject::getApprovalStatus, 1);

        List<ExecProject> execProjects = execProjectMapper.selectList(wrapper);

        execProjects.forEach(
                e->{
                    //合同
                    List<ExecProjectContract> execProjectContracts = projectContractList(e);
                    e.setContracts(execProjectContracts);
                }
        );
        return execProjects;
    }

    private List<ExecProjectContract> projectContractList(ExecProject project){

        //QueryWrapper<ExecProjectContract> wrapper = new QueryWrapper<>();
        //wrapper.lambda()
        //        .eq(ExecProjectContract::getProjectNumber, project.getProjectNumber())
        //        .eq(ExecProjectContract::getDel, 0);
        //List<ExecProjectContract> list = execProjectContractMapper.selectList(wrapper);

        QueryWrapper<ExecProjectContract> execProjectContractWrapper = new QueryWrapper<>();
        execProjectContractWrapper.lambda().eq(ExecProjectContract::getRelationId, project.getId());
        List<ExecProjectContract> execProjectContracts = execProjectContractMapper.selectList(execProjectContractWrapper);
        execProjectContracts.forEach(e ->{
            String achment = e.getAchment();
            if(org.apache.commons.lang3.StringUtils.isNotEmpty(achment)){
                e.setAchment("");
                e.setAttachment(JSONObject.parseArray(achment, Attachment.class));
            }
        });
        return execProjectContracts;
    }

    @Override
    public List<Customer> customerList(DevNeed devNeed) {

        QueryWrapper<Customer> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .eq(Customer::getState, 0);

        List<Customer> customers = customerMapper.selectList(wrapper);
        return customers;

    }

    @Override
    public List category(String type) {

        return categoryList;
    }

    @Override
    public Page<DevNeed> page(DevNeed devNeed) {
        //判断编号不为空查询project_id
        if(StringUtils.hasText(devNeed.getProjectNumber())){
            QueryWrapper<ExecProject> projectWrapper = new QueryWrapper<>();
            projectWrapper.lambda().eq(StringUtils.hasText(devNeed.getProjectNumber()), ExecProject::getProjectNumber, devNeed.getProjectNumber());
            //查询projectId

            List<ExecProject> execProject = execProjectMapper.selectList(projectWrapper);
            if(execProject.size()>0){
                devNeed.setProjectId(execProject.get(0).getId());
            }
        }
        QueryWrapper<DevNeed> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .eq(devNeed.getCategory() != null, DevNeed::getCategory, devNeed.getCategory())
                .like(StringUtils.hasText(devNeed.getNeedNo()), DevNeed::getNeedNo, devNeed.getNeedNo())
                .eq(StringUtils.hasText(devNeed.getUrgencyState()), DevNeed::getUrgencyState, devNeed.getUrgencyState())
                .ne(DevNeed::getDataState, 1)
                .eq(StringUtils.hasText(devNeed.getCustomerName()), DevNeed::getCustomerName, devNeed.getCustomerName())
                .eq(devNeed.getDevCreate() != null, DevNeed::getDevCreate, devNeed.getDevCreate())
                /*项目id*/
                .eq(devNeed.getProjectId() != null, DevNeed::getProjectId, devNeed.getProjectId()).orderByDesc(DevNeed::getId);
        Page<DevNeed> page = new Page<>(devNeed.getPage(), devNeed.getSize());
        Page<DevNeed> result = devNeedMapper.selectPage(page, wrapper);
        result.getRecords()
                .forEach(
                        e->{
                            QueryWrapper<NeedContract> contractWrapper = new QueryWrapper<>();
                            contractWrapper.lambda()
                                    .eq(NeedContract::getNeedId, e.getId())
                                    .eq(NeedContract::getDel, false);
                            List<NeedContract> needContracts = needContractMapper.selectList(contractWrapper);
                            e.setNeedContractList(needContracts);
                        }
                );

        return result;
    }

    @Override
    @Transactional
    public void del(Long id) {

        LambdaUpdateChainWrapper<DevNeed> wrapper = new LambdaUpdateChainWrapper<DevNeed>(devNeedMapper);
        boolean update = wrapper.eq(DevNeed::getId, id)
                .set(DevNeed::getDataState, 1)
                .set(DevNeed::getDelTime, LocalDateTime.now())
                .update();
    }

    @Override
    public Page<DevNeed> issuePage(DevNeed devNeed) {

        QueryWrapper<DevNeed> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .eq(DevNeed::getDataState, 2)
                .eq(devNeed.getCategory() != null, DevNeed::getCategory, devNeed.getCategory())
                .eq(StringUtils.hasText(devNeed.getCustomerName()), DevNeed::getCustomerId, devNeed.getCustomerName())
                .like(StringUtils.hasText(devNeed.getPreSalesName()), DevNeed::getPreSalesName, devNeed.getPreSalesName())
                .eq(StringUtils.hasText(devNeed.getUrgencyState()), DevNeed::getUrgencyState, devNeed.getUrgencyState())
                .ge(devNeed.getDeliveryDateLeft() != null, DevNeed::getDeliveryDate, devNeed.getDeliveryDateLeft())
                .le(devNeed.getDeliveryDateRight() != null, DevNeed::getDeliveryDate, devNeed.getDeliveryDateRight()).orderByDesc(DevNeed::getId);

        Page<DevNeed> page = new Page<>(devNeed.getPage(), devNeed.getSize());

        Page<DevNeed> result = devNeedMapper.selectPage(page, wrapper);

        return result;
    }

    @Override
    public Page<DevNeedIssue> issuedPage(DevNeed condition) {

        QueryWrapper<DevNeedIssue> wrapper = new QueryWrapper<>();

        wrapper.lambda()
                .eq(DevNeedIssue::getDataState, 0)
                .eq(condition.getProductCategoryId() != null, DevNeedIssue::getProductCategoryId, condition.getProductCategoryId())
                .eq(StringUtils.hasText(condition.getDevNeedCategory()), DevNeedIssue::getDevNeedCategory, condition.getDevNeedCategory())
                .eq(StringUtils.hasText(condition.getDevModel()), DevNeedIssue::getDevModel, condition.getDevModel())
                .eq(StringUtils.hasText(condition.getShuntDirection()), DevNeedIssue::getShuntDirection, condition.getShuntDirection()).orderByDesc( DevNeedIssue::getId);

        Page<DevNeedIssue> page = new Page<>(condition.getPage(), condition.getSize());

        Page<DevNeedIssue> result = devNeedIssueMapper.selectPage(page, wrapper);

        return result;
    }

    @Override
    public DevNeed devNeedDetail(DevNeed devNeed) {
        DevNeed devNeedList = devNeedMapper.selectById(devNeed.getId());
        //研发需求信息
                    //判断合同是否是手动输入的
        if(devNeedList!=null){
            if(devNeedList.getProjectId()!=null){
                //如果选择的，根据exe-project表查询
                //查询录入的表
                ExecProject execProject = execProjectMapper.selectById(devNeedList.getProjectId());

                QueryWrapper<ExecProjectContract> wrapper = new QueryWrapper<>();
                wrapper.lambda().eq(ExecProjectContract::getProjectNumber, execProject.getProjectNumber())
                        .eq(ExecProjectContract::getDel, 0);
                List<ExecProjectContract> list = execProjectContractMapper.selectList(wrapper);
                List<NeedContract> collect = list.stream()
                        .map(
                                es -> {
                                    NeedContract needContract = new NeedContract();
                                    needContract.setContactName(es.getContractName());
                                    needContract.setContractNo(es.getContractNo());
                                    needContract.setDeliveryDate(es.getDeliveryDate());
                                    needContract.setId(es.getId());
                                    needContract.setNeedId(es.getRelationId());
                                    needContract.setAttachments(JSONObject.parseArray(es.getAchment(), AttachmentDto.class));
                                    needContract.setProjectName(devNeedList.getProjectName());
                                    return needContract;
                                }
                        )
                        .collect(Collectors.toList());
                devNeedList.setNeedContractList(collect);
            }else{
                QueryWrapper<NeedContract> wrapper = new QueryWrapper<>();
                wrapper.lambda()
                        .eq(NeedContract::getNeedId, devNeed.getId())
                        .eq(NeedContract::getDel, false);
                List<NeedContract> list = needContractMapper.selectList(wrapper);
                list.forEach(
                        an->{
                            an.setProjectName(devNeedList.getProjectName());
                            an.setAttachments(JSONObject.parseArray(an.getAttachment(), AttachmentDto.class));
                        }
                );
                devNeedList.setNeedContractList(list);
            }
            //回填研发需求
            QueryWrapper<DevNeedInfo> infosQueryWrapper = new QueryWrapper<>();
            infosQueryWrapper.lambda().eq(DevNeedInfo::getDevNeedId, devNeedList.getId());
            List<DevNeedInfo> infos = devNeedInfoMapper.selectList(infosQueryWrapper);
            devNeedList.setInfos(infos);
            //回填需求分析
            QueryWrapper<NeedAnalyse> analysesQueryWrapper = new QueryWrapper<>();
            analysesQueryWrapper.lambda().eq(NeedAnalyse::getNeedId, devNeedList.getId()).eq(NeedAnalyse::getState, 0);
            List<NeedAnalyse> analyses = devNeedAnalyseMapper.selectList(analysesQueryWrapper);
            analyses.forEach(
                    an->{
                        an.setChargePersonName(devNeedList.getChargePersonName());
                        an.setAttachments(JSONObject.parseArray(an.getAttachmentRel(), AttachmentDto.class));
                    }
            );
            devNeedList.setAnalyses(analyses);
            DevNeedIssue devNeedIssue = devNeedIssueMapper.selectById(devNeedList.getIssueId());
            devNeedList.setIssue(devNeedIssue);
        }

        return devNeedList;
    }

    @Override
    public List<DevNeed>  devNeedProjectDetail(ExecProject execProject) {
        //查询DevNeed里面的对应的exeproject列表
        QueryWrapper<DevNeed> devNeedQueryWrapper = new QueryWrapper<>();
        devNeedQueryWrapper.lambda().eq(DevNeed::getProjectId, execProject.getId()).ne(DevNeed::getDataState,1);
        List<DevNeed> devNeedList  = devNeedMapper.selectList(devNeedQueryWrapper);
             //研发需求信息
        devNeedList.forEach(e->{
            //查询录入的表
            ExecProject execProjects = execProjectMapper.selectById(e.getProjectId());
            QueryWrapper<ExecProjectContract> wrapper = new QueryWrapper<>();
            wrapper.lambda().eq(ExecProjectContract::getProjectNumber, execProjects.getProjectNumber())
                    .eq(ExecProjectContract::getDel, 0);
            List<ExecProjectContract> list = execProjectContractMapper.selectList(wrapper);
            List<NeedContract> collect = list.stream()
                    .map(
                            es -> {
                                NeedContract needContract = new NeedContract();
                                needContract.setContactName(es.getContractName());
                                needContract.setContractNo(es.getContractNo());
                                needContract.setDeliveryDate(es.getDeliveryDate());
                                needContract.setId(es.getId());
                                needContract.setNeedId(es.getRelationId());
                                needContract.setAttachments(JSONObject.parseArray(es.getAchment(), AttachmentDto.class));
                                needContract.setProjectName(e.getProjectName());
                                return needContract;
                            }
                    )
                    .collect(Collectors.toList());
                    e.setNeedContractList(collect);

            //回填研发需求
            QueryWrapper<DevNeedInfo> infosQueryWrapper = new QueryWrapper<>();
            infosQueryWrapper.lambda().eq(DevNeedInfo::getDevNeedId, e.getId());
            List<DevNeedInfo> infos = devNeedInfoMapper.selectList(infosQueryWrapper);
            e.setInfos(infos);
            //回填需求分析
            QueryWrapper<NeedAnalyse> analysesQueryWrapper = new QueryWrapper<>();
            analysesQueryWrapper.lambda().eq(NeedAnalyse::getNeedId, e.getId()).eq(NeedAnalyse::getState, 0);
            List<NeedAnalyse> analyses = devNeedAnalyseMapper.selectList(analysesQueryWrapper);
            analyses.forEach(
                    an->{
                        an.setChargePersonName(e.getChargePersonName());
                        System.out.println(an.getAttachmentRel());
                        System.out.println(JSONObject.parseArray(an.getAttachmentRel(), AttachmentDto.class));
                        an.setAttachments(JSONObject.parseArray(an.getAttachmentRel(), AttachmentDto.class));
                    }
            );
            e.setAnalyses(analyses);
        });
        return devNeedList;
    }




    @Override
    public void createDevNeed(List<DevNeedInfo> infos) {

        if(!CollectionUtils.isEmpty(infos)){
            LambdaUpdateChainWrapper<DevNeed> wrapper = new LambdaUpdateChainWrapper<>(devNeedMapper);
            boolean update = wrapper.eq(DevNeed::getId, infos.get(0).getDevNeedId())
                    .set(DevNeed::getDevCreate, true)
                    .update();


            infos.forEach(
                    e->{
                        if(e.getId() == null){
                            e.setCreateTime(LocalDateTime.now());
                            devNeedInfoMapper.insert(e);
                        }else {
                            devNeedInfoMapper.updateById(e);
                        }
                    }
            );
        }

    }
    /*
    * 更新需求下发已下发*/
    @Override
    public ApiResult issueEdit(DevNeedIssue devNeedIssue) {
        //更新需求
        DevNeedIssue one = devNeedIssueMapper.selectById(devNeedIssue.getId());
        if(one!=null) {
            //更新下发表
            one.setDevNeedNo(generateDevNeedNo(devNeedIssue.getDevNeedCategory()));
            //查询对应的需求表id
            QueryWrapper<DevNeed> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("issue_id", devNeedIssue.getId());
            List<DevNeed> needList = devNeedMapper.selectList(queryWrapper);
            needList.forEach(
                    e -> {
                        LambdaUpdateChainWrapper<DevNeed> needWrapper = new LambdaUpdateChainWrapper<>(devNeedMapper);
                        boolean update = needWrapper.eq(DevNeed::getId, e.getId())
                                .eq(DevNeed::getDataState, 2)
                                .set(DevNeed::getDataState, 5)
                                .set(DevNeed::getIssueId, one.getId())
                                .update();
                    }
            );
        //更新
            devNeedIssueMapper.updateById(devNeedIssue);
        }
        return ApiResult.simpleSuccess();
    }

    @Override
    public String needNo(DevNeed devNeed) {

        QueryWrapper<DevNeed> wrapper = new QueryWrapper<>();
        wrapper.eq("category",devNeed.getCategory());
        wrapper.orderByDesc("create_time");
        wrapper.last("LIMIT 1");
        DevNeed need = devNeedMapper.selectOne(wrapper);
        String sub = "";
        if (need==null) {
            switch (devNeed.getCategory()) {
                case 1:
                    String a = "HT0001";
                    return a;
                case 2:
                    String b = "SQ0001";
                    return b;
                case 3:
                    String c = "SH0001";
                    return c;
                case 4:
                    String d = "GH0001";
                    return d;
            }
        }else {
            Integer number = Integer.valueOf(need.getNeedNo().substring(3, 6));
            number+=1;
            String lastNum = "";
            for (int i = 0; i<4 - number.toString().length();i++){
                lastNum += "0";
            }
            String s1 = String.valueOf(number);
            String s2 = need.getNeedNo().substring(1, 2);
            sub = s1+lastNum+s2;
        }
        return sub;
    }

}
